package com.dt.sns.elastic;

import java.io.IOException;
import java.util.ArrayList;
import java.util.List;

import org.apache.commons.lang3.exception.ExceptionUtils;
import org.elasticsearch.action.DocWriteRequest;
import org.elasticsearch.action.index.IndexRequest;
import org.elasticsearch.action.index.IndexResponse;
import org.elasticsearch.action.search.SearchRequest;
import org.elasticsearch.action.search.SearchResponse;
import org.elasticsearch.action.support.WriteRequest;
import org.elasticsearch.client.RequestOptions;
import org.elasticsearch.client.RestHighLevelClient;
import org.elasticsearch.common.unit.TimeValue;
import org.elasticsearch.common.xcontent.XContentType;
import org.elasticsearch.index.query.QueryBuilder;
import org.elasticsearch.search.SearchHit;
import org.elasticsearch.search.builder.SearchSourceBuilder;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import com.alibaba.fastjson.JSONObject;
import com.dt.sns.model.cms.Article;
import com.dt.sns.model.common.Page4Index;

@Service
public class ArticleDAO {

	private static Logger logger = LoggerFactory.getLogger(ArticleDAO.class);

	private static String index = "dt-blog-article";

	@Autowired
	private RestHighLevelClient restHighLevelClient;

	/**
	 * 查询方法
	 * 
	 * @param query
	 * @param pageData
	 * @return
	 */
	public Page4Index<Article> search(QueryBuilder query, Page4Index<Article> pageData) {
		List<Article> list = new ArrayList<>();
		SearchRequest searchRequest = new SearchRequest(ArticleDAO.index);
		SearchSourceBuilder searchSourceBuilder = new SearchSourceBuilder();
		searchSourceBuilder.query(query);
		searchSourceBuilder.from(pageData.getPageNo() - 1);
		searchSourceBuilder.size(pageData.getPageSize());
		searchSourceBuilder.sort(pageData.getSort(), pageData.getSortOrder());
		searchRequest.source(searchSourceBuilder);
		try {
			SearchResponse response = restHighLevelClient.search(searchRequest, RequestOptions.DEFAULT);
			Long totalRows = response.getHits().getTotalHits().value;
			pageData.init(totalRows.intValue(), pageData.getPageSize(), pageData.getPageNo() - 1);
			for (SearchHit hit : response.getHits().getHits()) {
				String body = hit.getSourceAsString();
				Article ir = JSONObject.parseObject(body, Article.class);
				list.add(ir);
			}
			pageData.setResult(list);
		} catch (IOException e) {
			logger.error(ExceptionUtils.getStackTrace(e));
		}
		return pageData;
	}

	/**
	 * 写索引方法
	 * 
	 * @param infoResult
	 */
	public void index(Article article) {
		long start = System.currentTimeMillis();
		IndexRequest indexRequest = new IndexRequest(ArticleDAO.index).id(article.getId().toString());
		indexRequest.source(JSONObject.toJSONString(article), XContentType.JSON);
		// 设置超时：等待主分片变得可用的时间
		indexRequest.timeout(TimeValue.timeValueSeconds(1));// TimeValue方式
		// 刷新策略
		indexRequest.setRefreshPolicy(WriteRequest.RefreshPolicy.NONE);// WriteRequest.RefreshPolicy实例方式
		// 操作类型
		indexRequest.opType(DocWriteRequest.OpType.INDEX);// DocWriteRequest.OpType方式
		// 同步执行
		try {
			IndexResponse indexResponse = restHighLevelClient.index(indexRequest, RequestOptions.DEFAULT);
			logger.info(article.toString() + ":" + indexResponse.getResult() + ":"
					+ (System.currentTimeMillis() - start) + "ms");
		} catch (IOException e) {
			logger.error(ExceptionUtils.getStackTrace(e));
		}

	}
}
